<script setup lang='ts'>
const { VITE_OFFICIAL_DOMAIN, VITE_CASINO_IMG_CLOUD_URL } = getEnv()
const { brandKf } = storeToRefs(useBrandStore())
const { userInfo, isLogin, logoAndIcoAndLoading, isShowCustomerService } = storeToRefs(useAppStore())
const { togleCustomerService } = useAppStore()

const isIframeLoaded = ref(false)
const time = ref(Date.now())

const { data: sign } = useRequest(ApiMemberBrandKefuSign, {
    ready: isLogin,
    manual: false,
})
const serviceUrl = computed(() => {
    if (!brandKf.value)
        return ''

    const detail = brandKf.value.find((item: any) => +item.state === 1)

    let str = ''
    if (isLogin.value && userInfo.value)
        str = `&username=${userInfo.value.username}&sign=${sign.value}`

    return detail && detail.url
        ? (`${detail.url}&lang=${getCurrentUrlLanguage()}${str}&VITE_OFFICIAL_DOMAIN=${VITE_OFFICIAL_DOMAIN}&LOGO_URL=${`${VITE_CASINO_IMG_CLOUD_URL}/${logoAndIcoAndLoading.value.logo_white}`}&time=${time.value}&app=1`)
        : ''
})
// iframe加载完成
function onIframeLoaded() {
    isIframeLoaded.value = true
}

function endChat() {
    togleCustomerService()
    setTimeout(() => {
        isIframeLoaded.value = false
        time.value = Date.now()
    }, 50)
}

watch(isShowCustomerService, (val) => {
    if (val) {
        document.body.classList.add('lock-scroll');
    } else {
        document.body.classList.remove('lock-scroll');
    }
}, { immediate: true })

</script>

<template>
    <teleport to="body">
        <transition name="kefu">
            <div v-show="isShowCustomerService" class="customer-service-wrapper">
                <div
                    class="absolute right-2 top-8 h-4 w-12 flex cursor-pointer items-center justify-center rounded-[10px] text-[20px] transition-all duration-100 text-white z-10"
                    @click="endChat">
                    <BaseIcon name="uni-close" />
                </div>
                <iframe :src="serviceUrl" frameborder="0" role="dialog" allowfullscreen name="intercom-messenger-frame"
                    title="Intercom live chat" @load="onIframeLoaded"></iframe>
            </div>
        </transition>

    </teleport>
</template>

<style lang='scss' scoped>
.customer-service-wrapper {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    z-index: 9999;
    transform-origin: right bottom;

    iframe {
        position: absolute;
        width: 100%;
        height: 100%;
        visibility: visible;
    }
}

.kefu-enter-active {
    transition: width 200ms, height 200ms, max-height 200ms, transform 300ms cubic-bezier(0, 1.2, 1, 1), opacity 83ms ease-out;
}

.kefu-enter-from {
    opacity: 0;
    transform: scale(0)
}
</style>